import axios from 'axios'

export default (options) => {
  const { axiosRequestConfig, tokenKey } = options

  const instance = axios.create(axiosRequestConfig)

  instance.interceptors.request.use(
    (config) => {
      const { successMsg, errorMsg, showLoading, needLogin } = config
      const token = options.getToken()

      // 需要登录
      if (needLogin && !token) return options.goLogin()

      // token
      config.headers[tokenKey] = token

      // 响应在200毫秒内不显示loading
      setTimeout(() => {
        if (showLoading && !config.done) options.showLoading(config)
      }, 150)

      config.onSuccess = (res) => {
        if (showLoading && config.loading) options.closeLoading(config)
        if (successMsg) options.message('success', typeof successMsg == 'string' ? successMsg : res.msg)
        return Promise.resolve(res.data)
      }

      config.onFail = (error, res) => {
        if (showLoading) options.closeLoading(config)
        if (errorMsg) options.message('error', error)
        return Promise.reject([error, res])
      }

      return config
    },
    (error) => {
      options.message('error', '请求超时!')
      return Promise.reject(error)
    }
  )

  instance.interceptors.response.use(
    (response) => {
      const { config } = response

      config.done = true

      if (config.showLoading) options.closeLoading(config)

      const { status, data } = response
      const reulst = data

      if (status && status == 200) {
        // 如果是文件流直接成功返回
        if (reulst instanceof Blob) {
          return config.onSuccess(response)
        }

        if (reulst.code == 0) {
          return config.onSuccess(reulst)
        } else {
          if (reulst.code == 401 || reulst.code == 402) options.goLogin(reulst)

          return config.onFail(reulst.msg, reulst)
        }
      } else {
        return config.onFail('数据解析异常', reulst)
      }
    },
    (error) => {
      const { config, response } = error

      if (config) config.done = true

      if (response) {
        let message
        if (response.status == 504 || response.status == 404) {
          message = '服务器异常'
        } else if (response.status == 403) {
          message = '权限不足,请联系管理员!'
        } else {
          message = '未知错误!'
        }

        return config.onFail(message, response.data)
      } else {
        if (config) {
          return config.onFail(error.message, error)
        } else {
          return Promise.reject([error.message, error])
        }
      }
    }
  )

  return instance
}
